//
//  lxbaseViewController.m
//  luodansc
//
//  Created by 方正国際 on 12/10/02.
//  Copyright (c) 2012年 方正株式会社. All rights reserved.
//

#import "lxbaseViewController.h"
#import "lxbaseEntity.h"
#import <MapKit/MapKit.h>
#import <QuartzCore/QuartzCore.h>
#import <Social/Social.h>
#import "lxWeiBoEntity.h"
#import <AudioToolbox/AudioToolbox.h>

#ifndef LUN_LOADING_VIEW_TAG
    #define LUN_LOADING_VIEW_TAG 1225
#endif

@interface lxbaseViewController ()

@end

@implementation lxbaseViewController
@synthesize is_loading = _is_loading;
@synthesize reFlash_bt = _reFlash_bt;
@synthesize is_supportShakeToEdit = _is_supportShakeToEdit;
@synthesize is_supportHandleSwipeFrom = _is_supportHandleSwipeFrom;

- (id)init {
    self = [super init];
    if (nil != self) {
        _is_loading = NO;
        _reFlash_bt = nil;
        _arrayMenuImageList = [[NSMutableArray alloc]initWithCapacity:6];
        _is_supportShakeToEdit = NO;
        _is_supportHandleSwipeFrom = NO;
        
        CGRect main_ret = [[UIScreen mainScreen] applicationFrame];
        self.view.frame = main_ret;
    }
    
    return self;
}

- (void)setIs_loading:(BOOL)is_loading {
    if (_is_loading == is_loading) {
        return;
    }
    _is_loading = is_loading;
    [self performAction];
}

- (void)performAction {
    if (YES == _is_loading) {
        [self showWaiting];
    } else {
        [self hideWaiting];
    }
}

- (void)showWaiting {
    int width = 32;
    int height = 32;
    
    CGRect ret = self.view.bounds;
    int x = ret.size.width;
    int y = ret.size.height;
    
    ret = CGRectMake((x - width) / 2, (y - height) / 2, width, height);
    UIActivityIndicatorView *loadView = [[UIActivityIndicatorView alloc] initWithFrame:ret];
    
    [loadView startAnimating];
    loadView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    
    ret = CGRectMake((x - 70) / 2, (y - height) / 2 + height, 80, 20);
    UILabel *waitingLable = [[UILabel alloc] initWithFrame:ret];
    waitingLable.text = NSLocalizedString(@"loading", nil);
    waitingLable.textColor = [UIColor whiteColor];
    waitingLable.font = [UIFont systemFontOfSize:15];
    waitingLable.backgroundColor = [UIColor clearColor];
    
    ret = self.view.bounds;
    UIView *theView = [[UIView alloc] initWithFrame:ret];
    theView.backgroundColor = [UIColor blackColor];
    theView.alpha = 0.7;
    
    [theView addSubview:loadView];
    [theView addSubview:waitingLable];
    
    [loadView release];
    [waitingLable release];
    
    [theView setTag:LUN_LOADING_VIEW_TAG];
    [self.view addSubview:theView];
    
    [theView release];
    
    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [spinner startAnimating];
    UIBarButtonItem *spinnerBt = [[UIBarButtonItem alloc] initWithCustomView:spinner];
    self.navigationItem.rightBarButtonItem = spinnerBt;
    
    [spinner release];
    [spinnerBt release];
}

- (void)hideWaiting {
    [[self.view viewWithTag:LUN_LOADING_VIEW_TAG] removeFromSuperview];
    if (nil != _reFlash_bt) {
        self.navigationItem.rightBarButtonItem = _reFlash_bt;
    }
}

- (BOOL)refreshData:(lxbaseEntity *)entity {
    if (nil == entity) {
        return NO;
    }
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    if (YES == _is_loading) {
        [self hideWaiting];
        _is_loading = NO;
    }
    if (nil != _reFlash_bt) {
        [_reFlash_bt release];
        _reFlash_bt = nil;
    }
    int count = [_arrayMenuImageList count];
    if (count > 5) {
        [_menu release];
    }
    [_arrayMenuImageList release];
    _is_supportShakeToEdit = NO;
    _is_supportHandleSwipeFrom = NO;
    [super dealloc];
}

#pragma mark -
#pragma mark QuadCurveMenuDelegate Methods
- (void)quadCurveMenu:(QuadCurveMenu *)menu didSelectIndex:(NSInteger)idx
{
    //    NSLog(@"Select the index : %d",idx);
    switch (idx) {
        case 0:
            [self clickMenuItem0];
            break;
        case 1:
            [self clickMenuItem1];
            break;
        case 2:
            [self clickMenuItem2];
            break;
        case 3:
            [self clickMenuItem3];
            break;
        case 4:
            [self clickMenuItem4];
            break;
        case 5:
            [self clickMenuItem5];
            break;
        default:
            break;
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft
        || interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        return NO;
    }
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        if (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown) {
            if (nil != _menu) {
                [_menu initScreenPoint:interfaceOrientation];
                [_menu setType:QuadCurveMenuTypeUpAndLeft];
            }
        }
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        if (nil != _menu) {
            [_menu initScreenPoint:interfaceOrientation];
            [_menu setType:QuadCurveMenuTypeUpAndLeft];
        }
        return YES;
    }
}

- (void)initMenu {
    UIImage *storyMenuItemImage = [UIImage imageNamed:@"story-button.png"];
    UIImage *storyMenuItemImagePressed = [UIImage imageNamed:@"story-button-pressed.png"];
    
    NSString* str = nil;
    UIImage *img = nil;
    
    str = [_arrayMenuImageList objectAtIndex:0];
    img = [UIImage imageNamed:str];
    QuadCurveMenuItem *enuItem0 = [[QuadCurveMenuItem alloc] initWithImage:storyMenuItemImage
                                                               highlightedImage:storyMenuItemImagePressed ContentImage:img highlightedContentImage:nil];

    str = [_arrayMenuImageList objectAtIndex:1];
    img = [UIImage imageNamed:str];
    QuadCurveMenuItem *enuItem1 = [[QuadCurveMenuItem alloc] initWithImage:storyMenuItemImage
                                                          highlightedImage:storyMenuItemImagePressed ContentImage:img highlightedContentImage:nil];

    str = [_arrayMenuImageList objectAtIndex:2];
    img = [UIImage imageNamed:str];
    QuadCurveMenuItem *enuItem2 = [[QuadCurveMenuItem alloc] initWithImage:storyMenuItemImage
                                                          highlightedImage:storyMenuItemImagePressed ContentImage:img highlightedContentImage:nil];
    
    str = [_arrayMenuImageList objectAtIndex:3];
    img = [UIImage imageNamed:str];
    QuadCurveMenuItem *enuItem3 = [[QuadCurveMenuItem alloc] initWithImage:storyMenuItemImage
                                                          highlightedImage:storyMenuItemImagePressed ContentImage:img highlightedContentImage:nil];
    
    str = [_arrayMenuImageList objectAtIndex:4];
    img = [UIImage imageNamed:str];
    QuadCurveMenuItem *enuItem4 = [[QuadCurveMenuItem alloc] initWithImage:storyMenuItemImage
                                                          highlightedImage:storyMenuItemImagePressed ContentImage:img highlightedContentImage:nil];
/*
    str = [_arrayMenuImageList objectAtIndex:5];
    img = [UIImage imageNamed:str];
    QuadCurveMenuItem *enuItem5 = [[QuadCurveMenuItem alloc] initWithImage:storyMenuItemImage
                                                          highlightedImage:storyMenuItemImagePressed ContentImage:img highlightedContentImage:nil];
*/    
    NSArray *menus = [NSArray arrayWithObjects:enuItem0, enuItem1, enuItem2, enuItem3, enuItem4, nil];
    [enuItem0 release];
    [enuItem1 release];
    [enuItem2 release];
    [enuItem3 release];
    [enuItem4 release];
//    [enuItem5 release];
    _menu = [[QuadCurveMenu alloc] initWithFrame:self.view.bounds menus:menus];
    _menu.delegate = self;

    [_menu setType:QuadCurveMenuTypeUpAndLeft];
    [self.view addSubview:_menu];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.

    [self subViewDidLoad];
    
    int cout = [_arrayMenuImageList count];
    if (cout > 5) {
        [self initMenu];
    }
    
    if (YES == _is_supportHandleSwipeFrom) {
        UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
        [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
        [[self view] addGestureRecognizer:recognizer];
        [recognizer release];
    }
}

- (lxWeiBoEntity *)getCurrentInfo {
    return nil;
}

- (void)clickMenuItem0 {
    //place
    if (SYSTEM_VERSION_LESS_THAN(@"6.0")) { // ios6以下，调用google map
        MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
        
        NSString *urlString = [[NSString alloc] initWithFormat:@"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f&dirfl=d", [currentLocation.placemark.location coordinate].latitude, [currentLocation.placemark.location coordinate].longitude, luodan_address_stationLat, luodan_address_stationLon];
        NSURL *aURL = [NSURL URLWithString:urlString];
        [urlString release];
        [[UIApplication sharedApplication] openURL:aURL];
    } else {
        CLLocationCoordinate2D to;
        to.latitude = luodan_address_stationLat;
        to.longitude = luodan_address_stationLon;
        MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
        MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[[MKPlacemark alloc] initWithCoordinate:to addressDictionary:nil] autorelease]];
        toLocation.name = NSLocalizedString(@"destination", nil);
        [MKMapItem openMapsWithItems:[NSArray arrayWithObjects:currentLocation, toLocation, nil]  launchOptions:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:MKLaunchOptionsDirectionsModeDriving, [NSNumber numberWithBool:YES], nil] forKeys:[NSArray arrayWithObjects:MKLaunchOptionsDirectionsModeKey, MKLaunchOptionsShowsTrafficKey, nil]]];
        [toLocation release];
    }
}

- (void)reFlash {}

- (void)clickMenuItem1 {
    [self reFlash];
}

- (void)clickMenuItem2 {
    //weibo
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeSinaWeibo]) {
        // 使用SLServiceTypeSinaWeibo来创建一个新浪微博view Controller
        SLComposeViewController *socialVC = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeSinaWeibo];
        // 写一个bolck，用于completionHandler的初始化
        SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result) {
            if (result == SLComposeViewControllerResultCancelled) {
                NSLog(@"cancelled");
            } else {
                NSLog(@"done");
            }
            [socialVC dismissViewControllerAnimated:YES completion:Nil];
        };
        // 初始化completionHandler，当post结束之后（无论是done还是cancell）该blog都会被调用
        socialVC.completionHandler = myBlock;
        // 给view controller初始化默认的图片，url，文字信息
        lxWeiBoEntity *lxWBE = [self getCurrentInfo];
        [socialVC setInitialText:lxWBE.text];
        [socialVC addImage:lxWBE.image];
        [socialVC addURL:lxWBE.url];
        
        // 以模态的方式展现view controller
        [self presentViewController:socialVC animated:YES completion:Nil];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                        message:NSLocalizedString(@"weibo_error", nil)
                                                       delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

- (void)clickMenuItem3 {
    //send mail
    MFMailComposeViewController *mailCompose = [[MFMailComposeViewController alloc] init];
    
    if (nil != mailCompose) {
        [mailCompose setMailComposeDelegate:self];
        
        NSArray *toRecipients = [NSArray arrayWithObject:to_mail];
        NSArray *bccRecipients = [NSArray arrayWithObject:bcc_mail];
        NSString *emailBody = NSLocalizedString(@"rodin_mind", nil);
        
        [mailCompose setToRecipients:toRecipients];
        [mailCompose setBccRecipients:bccRecipients];
        [mailCompose setMessageBody:emailBody isHTML:YES];
        [mailCompose setSubject:NSLocalizedString(@"contact_us", nil)];
        //        [mailCompose addAttachmentData:imageDate mimeType:@"image/jpg" fileName:@"1.png"];
        //open mail view
        //        [self presentModalViewController:mailCompose animated:YES];
        [self presentViewController:mailCompose animated:YES completion:nil];
    }
    
    [mailCompose release];
}

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    switch (result) {
        case MFMailComposeResultCancelled: {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"cancle", nil)
                                                            message:@""
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            
            [alert show];
            [alert release];
        }
            break;
        case MFMailComposeResultSaved: {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"saved_successfully", nil)
                                                            message:@""
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            
            [alert show];
            [alert release];
        }
            break;
        case MFMailComposeResultSent: {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"send_success", nil)
                                                            message:@""
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            
            [alert show];
            [alert release];
        }
            break;
        default: {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"send_failed", nil)
                                                            message:@""
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            
            [alert show];
            [alert release];
        }
            break;
    }
    //close mail view
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)clickMenuItem4 {
    //saveCurrentScreenToPhone
    UIGraphicsBeginImageContext(self.view.bounds.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(viewImage,nil, nil, nil);
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:NSLocalizedString(@"screen_shots", nil)
                                                   delegate:self
                                          cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                          otherButtonTitles:nil];
    
    [alert show];
    [alert release];
}

- (void)clickMenuItem5 {}

- (void)subViewDidLoad {}

//揺る揺る
- (BOOL)canBecomeFirstResponder {
    return _is_supportShakeToEdit;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (YES == _is_supportShakeToEdit) {
        [self becomeFirstResponder];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    if (YES == _is_supportShakeToEdit) {
        [self resignFirstResponder];
    }
    [super viewWillDisappear:animated];
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (YES == _is_supportShakeToEdit) {
        if (UIEventSubtypeMotionShake == motion) {
            [self reFlash];
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
            return;
        }
    }
    [super motionEnded:motion withEvent:event];
}

-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        NSLog(@"swipe right");
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end
